package by.grsu.mikhailava.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import by.grsu.mikhailava.entity.Question;
import by.grsu.mikhailava.table.QuestionTable;

import com.epam.grsulab.webapi.dao.AbstractDao;


public class QuestionDao extends AbstractDao<QuestionTable, Question> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 9132294099854063039L;

	public  QuestionDao(String rootFolderPath) {
		super(rootFolderPath);
	}
	
	public List<Question> searchByQuestionName(String name) {
		final QuestionTable questionTable = deserializeFromXml();
		List<Question> listQuestion = new ArrayList<Question>();
		for (Question q : questionTable.getRows()) {
			if (q.getQuestionName().equals(name)) {
				listQuestion.add(q);
			}
		}
		return listQuestion;
	}

	
	public void saveNew(Question newQuestion) {
		newQuestion.setId(getNextId());
		final QuestionTable questionTable = deserializeFromXml();
		questionTable.getRows().add(newQuestion);
		serializeToXml(questionTable);

	}

	@Override
	public void update(Question entity) {
		final QuestionTable questionTable = deserializeFromXml();
		for (Question q : questionTable.getRows()) {
			if (q.getId().equals(entity.getId())) {
				q.setSubjectId(entity.getSubjectId());
				q.setQuestionName(entity.getQuestionName());
			}
		}
		serializeToXml(questionTable);
	}

	@Override
	public Question get(Serializable id) {
		final QuestionTable questionTable = deserializeFromXml();
		for (Question q : questionTable.getRows()) {
			if (q.getId().equals(id)) {
				return q;
			}
		}
		return null;
	}

	@Override
	public List<Question> getAll() {
		QuestionTable questionTable = deserializeFromXml();
		return questionTable.getRows();
	}
	public List<Question> getBySubjectID(Serializable id) {
		final QuestionTable questionTable = deserializeFromXml();
		List<Question> question = new ArrayList<Question>();
		for (Question q : questionTable.getRows()) {
			if (q.getSubjectId().equals(id)) {
				question.add(q);
			}
		}
		return question;
	}
	@Override
	public void delete(Serializable id) {
		final QuestionTable questionTable = deserializeFromXml();
		Question questionToDelete = null;
		for (Question b : questionTable.getRows()) {
			if (b.getId().equals(id)) {
				questionToDelete = b;
			}
		}
		questionTable.getRows().remove(questionToDelete);
		serializeToXml(questionTable);
	}

	@Override
	protected Class<QuestionTable> getTableClass() {
		return QuestionTable.class;
	}
}
